package com.oneandone.httpserver.tcp.http.route;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import org.apache.log4j.Logger;

import com.oneandone.httpserver.tcp.http.request.HttpMethod;
import com.oneandone.httpserver.tcp.http.request.HttpRequest;
import com.oneandone.httpserver.tcp.http.response.HttpResponse;
import com.oneandone.httpserver.tcp.http.response.HttpStatus;

/**
 * @author calin
 */
public class BasicHttpRouter implements HttpRouter {
    private static final Logger LOGGER = Logger.getLogger(BasicHttpRouter.class);
	private ArrayList<Triplets> database = new ArrayList<Triplets>(); 
	
    @Override
    public void addRoute(HttpMethod method, String urlPattern, RequestHandler servler) {
        //To change body of implemented methods use File | Settings | File Templates.
    	database.add(new Triplets(method,urlPattern,servler));
    }

    @Override
    public RequestHandler findRoute(HttpMethod method, String url) {
        LOGGER.debug("Searching request handler for: " + method + " " +  url);
    	for (Triplets t : database){
        	if (t.method.equals(method) && !url.matches(t.urlPattern)){
        		LOGGER.debug("Request Handler found for " + method + " " + url);
        		return t.servler;
        	}
        }
    	LOGGER.debug("Request Handler not found for " + method + " " + url);
    	LOGGER.debug("Sending NOT_IMPLEMENTED status for " + method + " " + url);
    	return new RequestHandler() {
			@Override
			public HttpResponse handle(HttpRequest request) {
				return HttpResponse.status(HttpStatus.NOT_IMPLEMENTED);
			}
		};  //To change body of implemented methods use File | Settings | File Templates.
        
        
    }
    
    private class Triplets{
    	private HttpMethod method;
    	private String urlPattern;
    	private RequestHandler servler;
		public Triplets(HttpMethod method , String urlPattern, RequestHandler servler) {
			this.method = method;
			this.urlPattern = urlPattern;
			this.servler = servler;
		}
    	
    }
}
